﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 翻译姬 {
    /// <summary>
    /// 引用程序集：
    /// System.IO.Compression
    /// System.IO.Compression.FileSystem
    /// </summary>
    public class 工具类 {

        
        public static void 异步调用(string exe名, params string[] 参数) {
            异步调用(exe名, false, 参数);
        }
        public static void 异步调用(string exe名, bool 是否显示窗口 = false, params string[] 参数) {
            Process p = new Process();
            p.StartInfo.FileName = exe名;
            p.StartInfo.Arguments = string.Join(" ", 参数);
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = !是否显示窗口;
            p.Start();
            p.Close();
        }
        public static void 同步调用(string exe名, params string[] 参数) {
            同步调用(exe名, false, 参数);
        }
        public static void 同步调用(string exe名, bool 是否显示窗口 = false, params string[] 参数) {
            Process p = new Process();
            p.StartInfo.FileName = exe名;
            p.StartInfo.Arguments = string.Join(" ", 参数);
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = !是否显示窗口;
            p.Start();
            p.WaitForExit();
            p.Close();
        }
        public static string CMD同步调用(params string[] 参数) {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.StandardOutputEncoding = Encoding.Default;
            p.Start();
            p.StandardInput.WriteLine(string.Join(" ", 参数));
            p.StandardInput.AutoFlush = true;
            p.StandardInput.WriteLine("exit");
            string str = p.StandardOutput.ReadToEnd();
            p.StandardError.ReadToEnd();
            p.WaitForExit();
            p.Close();
            return str;
        }
        public static void CMD异步调用(params string[] 参数) {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.StandardOutputEncoding = Encoding.Default;
            p.Start();
            p.StandardInput.WriteLine(string.Join(" ", 参数));
            p.StandardInput.AutoFlush = true;
            p.StandardInput.WriteLine("exit");
            string str = p.StandardOutput.ReadToEnd();
            p.StandardError.ReadToEnd();
            p.Close();
        }

        /// <param name="标题">标题栏显示的标题</param>
        /// <param name="选择前缀">选择按钮上方显示的名字</param>
        /// <param name="filter">过滤的后缀，使用;分隔进行多选</param>
        /// <param name="起始目录">起始显示的目录</param>
        /// <param name="是否多选">是否允许多选</param>
        /// <returns></returns>
        public static string[] 选择文件(string 标题 = null, string 选择前缀 = "文件", string filter = null, string 起始目录 = null, bool 是否多选 = false) {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = 标题 == null ? "请选择文件" : 标题;
            if (起始目录 != null) {
                dialog.InitialDirectory = 起始目录;
            }
            dialog.Filter = filter == null ? 选择前缀 + "|*.*" : 选择前缀 + $"|{filter}";
            dialog.Multiselect = 是否多选;
            dialog.ShowDialog();
            return dialog.FileNames;
        }
        /// <returns>没选返回""</returns>
        public static string[] 选择文件夹(string 标题 = null, string 起始目录 = null, bool 是否多选 = false) {
            FolderSelectDialog dialog = new FolderSelectDialog();
            dialog.Title = 标题 == null ? "请选择文件夹" : 标题;
            if (起始目录 != null) {
                dialog.InitialDirectory = 起始目录;
            }
            dialog.Multiselect = 是否多选;
            if (dialog.ShowDialog()) {
                return dialog.FileNames;
            } else {
                return new string[0];
            }
        }
        public static string 选择保存目录(string 标题 = null, string 起始目录 = null, string 文件前缀 = "文件", string filter = null) {
            var info = new SaveFileDialog();
            info.Title = 标题;
            info.Filter = filter == null ? 文件前缀 + "|*.*" : 文件前缀 + $"|{filter}";
            info.AddExtension = true;
            info.AutoUpgradeEnabled = true;
            info.FileName = 起始目录;
            var r = info.ShowDialog();
            if (r != DialogResult.OK) {
                return null;
            }
            return info.FileName;
        }

    }


    #region 文件夹选择器
    /// <summary>
    /// Wraps System.Windows.Forms.OpenFileDialog to make it present
    /// a vista-style dialog.
    /// </summary>
    public class FolderSelectDialog {
        // Wrapped dialog
        System.Windows.Forms.OpenFileDialog ofd = null;

        /// <summary>
        /// Default constructor
        /// </summary>
        public FolderSelectDialog() {
            ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.AddExtension = false;
            ofd.CheckFileExists = false;
        }

        #region Properties

        /// <summary>
        /// Gets/Sets the initial folder to be selected. A null value selects the current directory.
        /// </summary>
        public string InitialDirectory {
            get { return ofd.InitialDirectory; }
            set { ofd.InitialDirectory = value == null || value.Length == 0 ? Environment.CurrentDirectory : value; }
        }

        /// <summary>
        /// Gets/Sets the title to show in the dialog
        /// </summary>
        public string Title {
            get { return ofd.Title; }
            set { ofd.Title = value == null ? "请选择文件夹" : value; }
        }

        /// <summary>
        /// Gets the selected folder
        /// </summary>
        public string FileName {
            get { return ofd.FileName; }
        }

        public bool Multiselect {
            get { return ofd.Multiselect; }
            set { ofd.Multiselect = value; }
        }

        public string[] FileNames {
            get { return ofd.FileNames; }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Shows the dialog
        /// </summary>
        /// <returns>True if the user presses OK else false</returns>
        public bool ShowDialog() {
            return ShowDialog(IntPtr.Zero);
        }

        /// <summary>
        /// Shows the dialog
        /// </summary>
        /// <param name="hWndOwner">Handle of the control to be parent</param>
        /// <returns>True if the user presses OK else false</returns>
        public bool ShowDialog(IntPtr hWndOwner) {
            bool flag = false;

            if (Environment.OSVersion.Version.Major >= 6) {
                var r = new Reflector("System.Windows.Forms");

                uint num = 0;
                Type typeIFileDialog = r.GetType("FileDialogNative.IFileDialog");
                object dialog = r.Call(ofd, "CreateVistaDialog");
                r.Call(ofd, "OnBeforeVistaDialog", dialog);

                uint options = (uint)r.CallAs(typeof(System.Windows.Forms.FileDialog), ofd, "GetOptions");
                options |= (uint)r.GetEnum("FileDialogNative.FOS", "FOS_PICKFOLDERS");
                r.CallAs(typeIFileDialog, dialog, "SetOptions", options);

                object pfde = r.New("FileDialog.VistaDialogEvents", ofd);
                object[] parameters = new object[] { pfde, num };
                r.CallAs2(typeIFileDialog, dialog, "Advise", parameters);
                num = (uint)parameters[1];
                try {
                    int num2 = (int)r.CallAs(typeIFileDialog, dialog, "Show", hWndOwner);
                    flag = 0 == num2;
                } finally {
                    r.CallAs(typeIFileDialog, dialog, "Unadvise", num);
                    GC.KeepAlive(pfde);
                }
            } else {
                var fbd = new FolderBrowserDialog();
                fbd.Description = this.Title;
                fbd.SelectedPath = this.InitialDirectory;
                fbd.ShowNewFolderButton = false;
                if (fbd.ShowDialog(new WindowWrapper(hWndOwner)) != DialogResult.OK) return false;
                ofd.FileName = fbd.SelectedPath;
                flag = true;
            }

            return flag;
        }

        #endregion
    }
    /// <summary>
    /// Creates IWin32Window around an IntPtr
    /// </summary>
    public class WindowWrapper : System.Windows.Forms.IWin32Window {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="handle">Handle to wrap</param>
        public WindowWrapper(IntPtr handle) {
            _hwnd = handle;
        }

        /// <summary>
        /// Original ptr
        /// </summary>
        public IntPtr Handle {
            get { return _hwnd; }
        }

        private IntPtr _hwnd;
    }
    /// <summary>
    /// This class is from the Front-End for Dosbox and is used to present a 'vista' dialog box to select folders.
    /// Being able to use a vista style dialog box to select folders is much better then using the shell folder browser.
    /// http://code.google.com/p/fed/
    ///
    /// Example:
    /// var r = new Reflector("System.Windows.Forms");
    /// </summary>
    public class Reflector {
        #region variables

        string m_ns;
        Assembly m_asmb;

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="ns">The namespace containing types to be used</param>
        public Reflector(string ns)
            : this(ns, ns) { }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="an">A specific assembly name (used if the assembly name does not tie exactly with the namespace)</param>
        /// <param name="ns">The namespace containing types to be used</param>
        public Reflector(string an, string ns) {
            m_ns = ns;
            m_asmb = null;
            foreach (AssemblyName aN in Assembly.GetExecutingAssembly().GetReferencedAssemblies()) {
                if (aN.FullName.StartsWith(an)) {
                    m_asmb = Assembly.Load(aN);
                    break;
                }
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Return a Type instance for a type 'typeName'
        /// </summary>
        /// <param name="typeName">The name of the type</param>
        /// <returns>A type instance</returns>
        public Type GetType(string typeName) {
            Type type = null;
            string[] names = typeName.Split('.');

            if (names.Length > 0)
                type = m_asmb.GetType(m_ns + "." + names[0]);

            for (int i = 1; i < names.Length; ++i) {
                type = type.GetNestedType(names[i], BindingFlags.NonPublic);
            }
            return type;
        }

        /// <summary>
        /// Create a new object of a named type passing along any params
        /// </summary>
        /// <param name="name">The name of the type to create</param>
        /// <param name="parameters"></param>
        /// <returns>An instantiated type</returns>
        public object New(string name, params object[] parameters) {
            Type type = GetType(name);

            ConstructorInfo[] ctorInfos = type.GetConstructors();
            foreach (ConstructorInfo ci in ctorInfos) {
                try {
                    return ci.Invoke(parameters);
                } catch { }
            }

            return null;
        }

        /// <summary>
        /// Calls method 'func' on object 'obj' passing parameters 'parameters'
        /// </summary>
        /// <param name="obj">The object on which to excute function 'func'</param>
        /// <param name="func">The function to execute</param>
        /// <param name="parameters">The parameters to pass to function 'func'</param>
        /// <returns>The result of the function invocation</returns>
        public object Call(object obj, string func, params object[] parameters) {
            return Call2(obj, func, parameters);
        }

        /// <summary>
        /// Calls method 'func' on object 'obj' passing parameters 'parameters'
        /// </summary>
        /// <param name="obj">The object on which to excute function 'func'</param>
        /// <param name="func">The function to execute</param>
        /// <param name="parameters">The parameters to pass to function 'func'</param>
        /// <returns>The result of the function invocation</returns>
        public object Call2(object obj, string func, object[] parameters) {
            return CallAs2(obj.GetType(), obj, func, parameters);
        }

        /// <summary>
        /// Calls method 'func' on object 'obj' which is of type 'type' passing parameters 'parameters'
        /// </summary>
        /// <param name="type">The type of 'obj'</param>
        /// <param name="obj">The object on which to excute function 'func'</param>
        /// <param name="func">The function to execute</param>
        /// <param name="parameters">The parameters to pass to function 'func'</param>
        /// <returns>The result of the function invocation</returns>
        public object CallAs(Type type, object obj, string func, params object[] parameters) {
            return CallAs2(type, obj, func, parameters);
        }

        /// <summary>
        /// Calls method 'func' on object 'obj' which is of type 'type' passing parameters 'parameters'
        /// </summary>
        /// <param name="type">The type of 'obj'</param>
        /// <param name="obj">The object on which to excute function 'func'</param>
        /// <param name="func">The function to execute</param>
        /// <param name="parameters">The parameters to pass to function 'func'</param>
        /// <returns>The result of the function invocation</returns>
        public object CallAs2(Type type, object obj, string func, object[] parameters) {
            MethodInfo methInfo = type.GetMethod(func, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            return methInfo.Invoke(obj, parameters);
        }

        /// <summary>
        /// Returns the value of property 'prop' of object 'obj'
        /// </summary>
        /// <param name="obj">The object containing 'prop'</param>
        /// <param name="prop">The property name</param>
        /// <returns>The property value</returns>
        public object Get(object obj, string prop) {
            return GetAs(obj.GetType(), obj, prop);
        }

        /// <summary>
        /// Returns the value of property 'prop' of object 'obj' which has type 'type'
        /// </summary>
        /// <param name="type">The type of 'obj'</param>
        /// <param name="obj">The object containing 'prop'</param>
        /// <param name="prop">The property name</param>
        /// <returns>The property value</returns>
        public object GetAs(Type type, object obj, string prop) {
            PropertyInfo propInfo = type.GetProperty(prop, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            return propInfo.GetValue(obj, null);
        }

        /// <summary>
        /// Returns an enum value
        /// </summary>
        /// <param name="typeName">The name of enum type</param>
        /// <param name="name">The name of the value</param>
        /// <returns>The enum value</returns>
        public object GetEnum(string typeName, string name) {
            Type type = GetType(typeName);
            FieldInfo fieldInfo = type.GetField(name);
            return fieldInfo.GetValue(null);
        }

        #endregion

    }
    #endregion
}
